<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="ID">
                <a-input v-model="queryParam.id" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input v-model="queryParam.name" placeholder="" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              
            </template>
            <!-- <a-col :md="(!advanced && 8) || 24" :sm="24"> -->
            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <!-- <a-button type="primary" icon="plus" @click="handleAdd"  v-action:financeLog_add>新建</a-button> -->
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" showPagination="auto" :scroll="{ x: 'auto' }">
        <span slot="param" slot-scope="text">
          <div class="param-wrap">{{ text }}</div>
        </span>
        <span slot="ftype" slot-scope="text, record">
          {{record.typeId1Name}}{{record.typeId2Name?` - ${record.typeId2Name}`:''}}
        </span>
        <span slot="status" slot-scope="text">
          <a-tag :color="text | statusFilter(financeStatusList, 'status')">{{ text | statusFilter(financeStatusList, 'name') }}</a-tag>
        </span>
        <span slot="atta" slot-scope="text">
          <template>
            <AWM-file-list :list="text"></AWM-file-list>
          </template>
        </span>
        <span slot="remark" slot-scope="text">
          <template>
            <div class="remark-wrap">{{ text }}</div>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:financeLog_update>编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)" v-action:financeLog_update>删除</a>
            <!-- <a-divider type="vertical" />
            <a @click="handleMakeInvoice(record)" v-if="record.invoiceStatus == 0">开票</a>
            <a @click="checkInvoice(record)" v-else>开票信息</a> -->
          </template>
        </span>
      </s-table>
      <!-- IncomeForm -->
      <sms-curtail-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :typeList="typeList"
        :needList="needList"
        :financeTypeList="financeTypeList"
        :showSave="false"
        @cancel="handleCancel"
        @ok="handleOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis, AWMFileList } from '@/components'
// import {  eachMap, financeStatusList } from '@/utils/other'
import { financeStatusList, typeList, invoiceTypeList, needList } from '@/utils/other'
import { financeLogUpdate, financeInvoiceAdd } from '@/api/finance'
import SmsCurtailForm from './modules/SmsCurtailForm'
import { Cascader } from 'ant-design-vue'
import { changeUrlQuery } from '@/utils/util'
import {
  getSmsCurtailList,
  getSmsCurtailAdd,
  getSmsCurtailUpdate,
} from '@/api/sms'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    fixed:true,
  },
  {
    title: '用户',
    dataIndex: 'name',
    key: 'name',
    width:'200px',
    fixed:true,
  },
  {
    title: '数量范围',
    dataIndex: 'ftype',
    width:'200px',
    scopedSlots: { customRender: 'ftype' },
  },
  {
    title: '缩减比例',
    width:'200px',
    dataIndex: 'rate',
  },
  {
    title: '添加人',
    width:'230px',
    dataIndex: 'contract',
    scopedSlots: { customRender: 'contract' },
  },
  {
    title: '添加时间',
    dataIndex: 'amount1',
    width: 100,
    resizable:true,
  },
  {
    title: '最后修改时间',
    dataIndex: 'amount2',
    width: 100,
    resizable:true,
  },
  {
    title: '最后修改人',
    dataIndex: 'amount3',
    width: 100,
    resizable:true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'AWM-TypeList',
  components: {
    STable,
    Ellipsis,
    SmsCurtailForm,
    AWMFileList,
    'a-cascader': Cascader,
  },
  data() {
    this.columns = columns
    return {
      open: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      invoice:{
        visible: false,
        confirmLoading: false,
        mdl: null,
        data:{},
      },
      details:{
        visible: false,
        confirmLoading: false,
        id:null
      },
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam:{},
      data: [],
      // 状态
      financeTypeList:[],   // 财务具体事项
      financeStatusList, // 申请状态
      typeList, // 收入或支出列表
      invoiceTypeList,
      needList,
      // 排序
      sortJ: {
        addTime: 'add_time',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        // 附加属性
        let subParam = {}
        const requestParameters = Object.assign({}, parameter, this.queryParam, subParam)

        if( requestParameters.typeId1 ){
          if( requestParameters.typeId1.length == 2 ){
            requestParameters.typeId2 = requestParameters.typeId1[1]
          }
          requestParameters.typeId1 = requestParameters.typeId1[0]
        }
        if (requestParameters.buildTime) {
          requestParameters.startTime = requestParameters.buildTime[0].format('YYYY-MM-DD HH:mm:ss')
          requestParameters.endTime = requestParameters.buildTime[1].format('YYYY-MM-DD HH:mm:ss')
          delete requestParameters.buildTime
        }
        return getSmsCurtailList(requestParameters).then((res) => {
          let newQuery = requestParameters;
          delete newQuery.type
          delete newQuery.pageSize
          delete newQuery.pageNo
          delete newQuery.typeId1
          
          this.$router.push({ path:this.$route.path,query: newQuery })

          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {
    let query = this.$route.query
    
    for(let i in query){
      if(i.indexOf('typeDetailBy')!= -1){
        // 列表
        let matching = {
          typeDetailByClient: this.getClientList,
          typeDetailByEpiboly: this.getEpibolyList,
          typeDetailByFiliale: this.getFilialeList,
          typeDetailByProject: this.getProjectList,
          typeDetailByStudio: this.getStudioList
        }
        query[i] = Number(query[i])
        matching[i]('',query[i])
      }else if( i == 'startTime' && query.endTime){
        query.buildTime = [moment(query.startTime), moment(query.endTime)]
        // 时间
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const createModal = this.$refs.createModal
      const form = createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            getSmsCurtailUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            getSmsCurtailAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      if(!this.open && !this.advanced){
        this.open = true
        this.getClientList('','',true)
        this.getEpibolyList('','',true)
        this.getFilialeList('','',true)
        this.getProjectList('','',true)
        this.getStudioList('','',true)
        this.getTbList('','',true)
      }
      this.advanced = !this.advanced
    },
    
    handleDel(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '支出明细删除',
        content: `是否删除收入明细:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDelete(a_record.id, modal),
        onCancel: () => {},
      })
    },

    handleDelete(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        financeLogUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
    handleMakeInvoice(record){
      this.invoice.mdl = null
      this.invoice.visible = true
      this.invoice.data = record
    },
    handleInvoiceCancel(){
      this.invoice.visible = false
      const form = this.$refs.invoiceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleInvoiceOk(a_id){
      const createModal = this.$refs.invoiceModal
      const form = createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          
          values.sendTime?values.sendTime = values.sendTime.format("YYYY-MM-DD HH:mm:ss"):''
          delete values.id
          delete values.logName
          values.logId = a_id
            financeInvoiceAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
        } else {
          this.confirmLoading = false
        }
      })
    },
    checkInvoice(record){
      this.details = {
        visible: true,
        id: record.id
      }
    },
    handleDetailsCancel(){
      this.details = {
        visible: false,
        id: null
      }
    }
  },
}
</script>
<style scoped lang="less">
.param-wrap {
  min-width: 200px;
  max-width: 300px;
}

.a-tag-wrap{
  font-size: 12px;
  /deep/ .ant-tag{
    line-height:18px;
    padding: 0 4px;
  }
  div{
    margin-bottom: 2px;
    &:last-child{
      margin-bottom: 0;
    }
  }
}
</style>



 